//
//  AddMyStockListController.m
//  Stock
//
//  Created by blacksun on 11-6-18.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "AddMyStockListController.h"


@implementation AddMyStockListController
@synthesize leftButton;
@synthesize searchBar;
@synthesize tableView;
@synthesize stockService;
@synthesize stocks;
@synthesize selectedStocks;
@synthesize parentController;
@synthesize searchButton;

- (void)dealloc
{
    [self.stockService cancleAllRequest];
    self.stockService = nil;
    self.leftButton = nil;
    self.searchBar = nil;
    self.tableView = nil;
    self.stocks = nil;
    self.selectedStocks = nil;
    self.searchButton = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    for (MyStock *toAddStock in selectedStocks) {
        BOOL exist = NO;
        for (MyStock *favoriteStock in parentController.localStocks) {
            if ([favoriteStock.uuid isEqualToString:toAddStock.uuid]) {
                exist = YES;
                break;
            }
        }
        if (!exist) {
            [parentController.localStocks addObject:toAddStock];
            [[StockContext shareInstance].remoteMyStocks addObject:toAddStock];
            [toAddStock save];
            [stockService addMyStockWithIds:toAddStock.uuid];
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.stockService = [[[MyStockService alloc] initWithDelegate:self] autorelease];
    self.stocks = [NSArray array];
    self.selectedStocks = [NSMutableArray array];
    
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0.0, 427.5, 105.0, 52.5);
    //doneButton.adjustsImageWhenHighlighted = NO;
    doneButton.showsTouchWhenHighlighted = YES;
    [doneButton setBackgroundImage:[UIImage imageNamed:@"query.png"] forState:UIControlStateNormal];
    [doneButton setTitle:@"查询" forState:UIControlStateNormal];
    [doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.searchButton = doneButton;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden) name:UIKeyboardWillHideNotification object:nil];
    
    [self.searchBar becomeFirstResponder];
}
- (void)keyboardWillShow:(NSNotification *)note {
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    [tempWindow addSubview:searchButton];
    UILabel *titleLabel = searchButton.titleLabel;
    titleLabel.font = [UIFont boldSystemFontOfSize:20.0];
    titleLabel.shadowOffset = CGSizeMake(-0.5, -1.0);
    titleLabel.shadowColor = [UIColor grayColor];
    
    
}
-(void)doneButton:(id)sender{
    [self searchBarSearchButtonClicked:self.searchBar];
}

-(void)keyboardDidHidden{
    NSLog(@"keyboardDidHidden");
    [self.searchButton removeFromSuperview];
}   

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.leftButton = nil;
    self.searchBar = nil;
    self.tableView = nil;
}



-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    self.stocks = aResult;
    [self.tableView reloadData];
}
-(void)requestFinishedwithError:(NSError *)aError andUserinfo:(NSDictionary *)aUserinfo{
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)aSearchBar{
    //NSLog(@"search %@",aSearchBar.text);
    if (searchBar.text.length==0) {
        return;
    }
    [self.searchBar resignFirstResponder];
    [self.stockService cancleAllRequest];
    [self.stockService queryStock:aSearchBar.text];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)aSearchBar{
    
    [self.stockService cancleAllRequest];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (searchText.length>0) {
        [searchButton setBackgroundImage:[UIImage imageNamed:@"confirm.png"] forState:UIControlStateNormal];
        [searchButton setTitle:@"确定" forState:UIControlStateNormal];
    }else{
        [searchButton setBackgroundImage:[UIImage imageNamed:@"query.png"] forState:UIControlStateNormal];
        [searchButton setTitle:@"查询" forState:UIControlStateNormal];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.stocks count];
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"addMyStock";
    
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.textColor = [UIColor whiteColor];
    }
    MyStock *myStock = [self.stocks objectAtIndex:[indexPath row]];
    NSString *imageName = @"cellbg1.png";
    if (indexPath.row%2==1) {
        imageName = @"cellbg2.png";
    }
    cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]] autorelease];
    cell.textLabel.text = myStock.name;
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MyStock *stock = [self.stocks objectAtIndex:indexPath.row];
    UITableViewCell *cell = [aTableView cellForRowAtIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if ([self.selectedStocks containsObject:stock]) {
        [self.selectedStocks removeObject:stock];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }else{
        [selectedStocks addObject:stock];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

@end
